import os,json

from flask import request
from SQLOperation.PatientSQLOperation import PatientSQLOperation
from SQLConfig import app
from Interface import Interface
import constants
from routes.punctuation import getStlFileName, getPuncFilePath
from updateProjectFile import changeProjectFile

@app.route('/analyse', methods=['Get', 'POST'])
def analyse():  # put application's code here
    """
    调用C++进行分析模拟
    """
    # 判断是否存在此用户
    patientId = request.json.get("patientId")
    user = PatientSQLOperation.searchById(patientId)
    if user is None:
        return "patient not exist"
    indexAim_up = request.json.get("indexAim_up")
    indexIn_up = request.json.get("indexIn_up")
    indexAim_down = request.json.get("indexAim_down")
    indexIn_down = request.json.get("indexIn_down")
    
    patientId=str(patientId)
    stl1=os.path.join(constants.patientBaseUrl, patientId, constants.patientStlUrl, getStlFileName(patientId,indexAim_up))
    stl2=os.path.join(constants.patientBaseUrl, patientId, constants.patientStlUrl, getStlFileName(patientId,indexIn_up))

    stl3=os.path.join(constants.patientBaseUrl, patientId, constants.patientStlUrl, getStlFileName(patientId,indexAim_down))
    stl4=os.path.join(constants.patientBaseUrl, patientId, constants.patientStlUrl, getStlFileName(patientId,indexIn_down))

    pointAim ,pointIn = getPuncFilePath(patientId, getStlFileName(patientId,indexAim_up), getStlFileName(patientId,indexIn_up))

    # return json.dumps({
    #     "success":True,
    #     "k1_b1_k2_b2":[-0.23294730242935519, 
    #     30.69846194667739, 
    #     -0.830133234833552, 
    #     266.29863093386683],
    #     "matrix":[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]
    #     })
    
    # 根据size的大小对两个stl点云数据进行降采样，减少点的数量
    target, source = Interface.under_sample(constants.size, stl1, stl2)

    # 根据用户标点，获得大致的变换矩阵
    matrix1 = Interface.abs_rotation(pointAim, pointIn)

    # 对上颌进行配准
    matrix2 = Interface.add_align(target, source, constants.iterations, matrix1)
    
    # 对下颌进行操作，求解出对应点
    list1, list2 = Interface.key_points(stl3, stl4, constants.iterations, matrix2)

    # 根据下颌求得的对应点，求解旋转轴
    k1, b1, k2, b2 = Interface.compute_axis(list1[0], list1[1], list2)

    changeProjectFile(patientId, "information","update","rotationAxis",[k1,b1,k2,b2])
    changeProjectFile(patientId, "information","update","transformMatrix",matrix2)

    return json.dumps({
        "success": True,
        "k1_b1_k2_b2": [k1,b1,k2,b2],
        "matrix": matrix2
    })
